const express = require('express');
const router = express.Router();
const {checkRegister, register} = require('../controller/register');
const {SuccessModel, ErrorModel} = require('../model/resModel');

router.get('/', function (req, res) {
    res.render('register', {title: '注册'})
});

router.post('/in', function (req, res, next) {
    const {realname, username, password, repeatePassword} = req.body;
    if (username === '') {
        res.json(
            new ErrorModel('用户名不能为空')
        );
    } else if (password === '') {
        res.json(
            new ErrorModel('密码不能为空')
        );
    } else if (password !== repeatePassword) {
        res.json(
            new ErrorModel('两次输入的密码不一样')
        );
    } else {
        let result = checkRegister(username);
        return result.then(data => {
            if (data.id) {
                res.json(
                    new ErrorModel('用户名已存在')
                );
            } else {
                let result = register(realname, username, password);
                return result.then(data => {
                    res.json(
                        new SuccessModel({
                            username: username,
                            realname: realname
                        })
                    )
                })
            }
        })
    }

});

module.exports = router;